<template>
  <div class="upload-file">
    <el-upload
      :multiple="props.multiple"
      :http-request="httpRequest"
      :file-list="fileList"
      :limit="limit"
      :show-file-list="false"
      class="upload-file-uploader"
      ref="fileUpload"
    >
      <!-- 上传按钮 -->
      <!-- <el-button type="primary">选取文件</el-button> -->
      <el-button text><svg-icon class="mr-1" icon-class="add1" /> 文件上传</el-button>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
      </template>
      的文件
    </div>
    <!-- 文件列表 -->
    <transition-group class="flex flex-wrap" name="el-fade-in-linear" tag="ul">
      <div
        class="mb-4 mr-10 flex items-center"
        v-for="(file, index) in fileList"
        :key="index"
      >
        <svg-icon class="mr-2" icon-class="file"></svg-icon>
        <span class="mr-2 link-style">
          <span class="el-icon-document"> {{ file.name }} </span>
        </span>
        <el-button type="primary" link @click="handleDownload(file)">下载</el-button>
        <div class="ele-upload-list__item-content-action">
          <svg-icon
            class="text-red-500"
            icon-class="del"
            @click="handleDelete(index)"
          ></svg-icon>
        </div>
      </div>
    </transition-group>
    <el-progress
      v-if="props.progress && progressPercent"
      class="mt-1"
      :percentage="progressPercent"
      :width="128"
    />
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { uploadFile } from "@/api/index";
import { downLoadImage, downloadFile } from "@/utils/downloadFile.js";

const props = defineProps({
  modelValue: {
    type: [String, Array],
    default: "",
  },
  // 数量限制
  limit: {
    type: Number,
    default: 0,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 100,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["doc", "xls", "ppt", "txt", "pdf"],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true,
  },
  progress: { type: Boolean, default: false }, // 是否使用进度条
  multiple: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const fileList = ref([]);
const progressPercent = ref(0);
watch(progressPercent, (val) => {
  if (val === 100) {
    const timer = setTimeout(() => {
      progressPercent.value = 0;
      clearTimeout(timer);
    }, 1000);
  }
});
const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      let temp = 1;
      // 首先将值转为数组
      if (JSON.stringify(val) == "{}") {
        val = [];
      }
      const list = Array.isArray(val) ? val : props.modelValue.split(",");
      // 然后将数组转为对象数组
      fileList.value = list.map((item) => {
        if (typeof item === "string") {
          item = { name: item, url: item };
        }
        item.uid = item.uid || new Date().getTime() + temp++;
        return item;
      });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);

// 删除文件
function handleDelete(index) {
  fileList.value.splice(index, 1);
  emit("update:modelValue", fileList.value);
}

const httpRequest = (fileData) => {
  const { file } = fileData;
  let formData = new FormData();
  formData.append("file", file);
  uploadFile(formData, handleUploadProgress).then((res) => {
    fileList.value = fileList.value
      .filter((f) => f.url !== undefined)
      .concat({ name: res.data["filename"], url: res.data["data-show-file"] });
    uploadList.value = [];
    number.value = 0;
    ElMessage.success("上传成功");
    emit("update:modelValue", fileList.value);
  });
};

const handleUploadProgress = (event) => {
  if (event.lengthComputable) {
    progressPercent.value = (event.loaded / event.total).toFixed(2) * 100;
  }
};

const handleDownload = (file) => {
  const { url, name } = file;
  const imageExtensions = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg"];
  const lowerCaseUrl = url.toLowerCase();
  const isImage = imageExtensions.some((ext) => lowerCaseUrl.endsWith(ext));
  console.log("isImage");
  console.log(isImage);

  if (isImage) {
    downLoadImage(url);
  } else {
    downloadFile(url, name, false);
  }
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

.link-style {
  width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
